/**
 * 
 */
package org.rico.server;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.rico.server.cache.Cache;
import org.rico.server.cache.CacheBuilder;
import org.rico.server.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * sso server 登录sevlet
 * @author rico
 */
public class AuthenticateServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(AuthenticateServlet.class);
	
	// session/token map
	private static Map<String, String> serverMap = new ConcurrentHashMap<>();

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	/* 登录操作
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = (String) req.getParameter("username");
		String password = (String) req.getParameter("password");
		String backUrl = (String) req.getParameter("backUrl");
		String systemId = (String) req.getParameter("systemId");
		
		// 登录处理
		boolean result = this.handleLogin(username, password);
		logger.info("server handle login[result={}, username={}, password={}, systemId={}]", new Object[]{result, username, password, systemId});
		
		if(!result) {
			// 用户验证失败，重新登录页面
			logger.info("login fail, redirect to login page");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
			
		} else {
			// 登录成功，返回结果sso-client
			String token = UUID.randomUUID().toString();
			req.getSession().setAttribute("isLogin", true);
			this.handleResult(systemId, backUrl, token, resp);
		}
	}
	
	/**
	 * 验证用户信息
	 * @param username
	 * @param password
	 * @return
	 */
	private boolean handleLogin(String username, String password) {
		if("admin".equals(username) && "123456".equals(password)) {
			return true;
		}
		return false;
	}
	
	/**
	 * 处理登录结果
	 * @param backUrl
	 * @param token
	 * @param resp
	 * @throws IOException
	 */
	private void handleResult(String systemId, String backUrl, String token, HttpServletResponse resp) throws IOException {
		StringBuffer buff = new StringBuffer(backUrl);
		buff.append("?token=").append(token);
		logger.info("handle result[backUrl={}]", buff.toString());
		
		//TODO save login state
		for(SystemEnum item : SystemEnum.values()) {			
			CacheBuilder builder = new CacheBuilder();
			Cache cache = builder.systemId(item.getValue())
					.token(token)
					//.url(backUrl)
					.toCache();
			CacheManager.put(item.getValue(), cache);
		}
		
		resp.sendRedirect(buff.toString());
	}
}
